package com.lvgroup.hospital.base

import android.content.Intent
import android.os.Bundle
import android.os.Handler
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import androidx.lifecycle.GenericLifecycleObserver
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleOwner
import butterknife.ButterKnife
import butterknife.Unbinder
import com.baidu.mobstat.StatService
import com.chookss.MyApp
import com.chookss.R
import com.chookss.base.AppStatus
import com.chookss.base.AppStatusManager
import com.chookss.base.Token
import com.chookss.login.LoginActivity
import com.chookss.login.SplashActivity
import com.chookss.tools.MyEvent
import com.chookss.view.InitDialog
import com.chookss.view.listener.ShareDialogListener
import com.gyf.immersionbar.ImmersionBar
import com.johnrambo.ktea.base.BaseActivity
import com.johnrambo.ktea.ktExtends.startActivity
import com.lzy.okgo.OkGo
import com.noober.background.BackgroundLibrary
import infoToast
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import java.util.*


/**
 * Create by JohnRambo at 2018/12/17
 */
abstract class BaseAct : BaseActivity() {
    private var unbinder: Unbinder? = null
    override var loadingMilliSeconds = 300L
    override fun tokenLoseDoing() {
        Token.quit()
        infoToast("登陆信息已过期, 请重新登陆.")
        startActivity<LoginActivity>()
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        validateAppStatus();
        BackgroundLibrary.inject(this);
        lifecycle.addObserver((GenericLifecycleObserver { source: LifecycleOwner?, event: Lifecycle.Event ->
            if (event == Lifecycle.Event.ON_DESTROY) try {
                OkGo.getInstance().cancelTag(this@BaseAct)
            } catch (e: Exception) {
            }
        } as GenericLifecycleObserver)!!)
        // 绑定
        EventBus.getDefault().register(this);
        val handler = Handler()
        with(window.decorView) {
            post {
                handler.post {
                    initData()
                }
            }
        }
    }
    /**
     * 本方法初始化数据
     */
    abstract fun initData()

    fun validateAppStatus(){
         var appStatus:Int  = AppStatusManager.getInstance().getAppStatus();
        if(appStatus == AppStatus.STATUS_RECYVLE||isDestroyed||isFinishing||this==null){
            //异常退出
            protectApp();
        }else if(appStatus == AppStatus.STATUS_NORMAL){
            //不需要处理或者初始方法调用
        }
    }
    fun protectApp() {
        if (!MyApp.isSplash) {
            MyApp.isSplash = true
            MyApp.exitApp()
            MyApp.init()
            val intent =
                Intent(this, SplashActivity::class.java)
            intent.putExtra("type", 1)
            startActivity(intent)
            finish()
            return
        }
    }
    override fun setContentView(view: View?) {
        super.setContentView(view)
        if (view !is FrameLayout) { /*避免销毁内存时再次注册butterknife*/
            unbinder = ButterKnife.bind(this)
        }
    }

    override fun setContentView(view: View?, params: ViewGroup.LayoutParams?) {
        super.setContentView(view, params)
        unbinder = ButterKnife.bind(this)
    }

    override fun setContentView(layoutResID: Int) {
        super.setContentView(layoutResID)
        unbinder = ButterKnife.bind(this)
    }

    /**
     * 普通沉浸式状态栏
     */
    open fun initState() {
        ImmersionBar.with(this)
            .transparentStatusBar() /*透明状态栏，不写默认透明色*/.statusBarColor(R.color.white)
            .statusBarDarkFont(true) /*状态栏字体是深色，不写默认为亮色*/
            .flymeOSStatusBarFontColor(R.color.grey_3) /*修改flyme OS状态栏字体颜色*/
            .keyboardEnable(false).navigationBarEnable(false)
            .init()
    }

    /**
     * 沉浸式状态栏  通顶的
     */
    open fun initState2() {
        ImmersionBar.with(this)
            .transparentStatusBar() /*透明状态栏，不写默认透明色*/ /*状态栏字体是深色，不写默认为亮色*/
            .statusBarDarkFont(false)
            .flymeOSStatusBarFontColor(R.color.white) /*修改flyme OS状态栏字体颜色*/
            .keyboardEnable(false).navigationBarEnable(false)
            .init()
    }
    /**
     * 沉浸式状态栏  专门针对一些低版本手机顶部异常
     */
    open fun initState3() {
        ImmersionBar.with(this)
            .transparentStatusBar() /*透明状态栏，不写默认透明色*/ /*状态栏字体是深色，不写默认为亮色*/
            .statusBarColor(R.color.white)
            .statusBarDarkFont(true)
            .fitsSystemWindows(true)
            .flymeOSStatusBarFontColor(R.color.grey_3) /*修改flyme OS状态栏字体颜色*/
            .keyboardEnable(false).navigationBarEnable(false)
            .init()
    }

    override fun onDestroy() { /*兼容14之前的版本需要在基类中添加以下代码*/
        if (null != unbinder) unbinder!!.unbind()
        // 解绑
        EventBus.getDefault().unregister(this);
        super.onDestroy()
    }

    /**
     * 默认绑定一个事件，防止源码里面去找方法的时候找不到报错。
     * @param activity
     */
    @Subscribe
    open fun onEvent(activity: BaseActivity?) {
    }

    override fun onPause() {
        super.onPause()
        if(MyApp.privacyPermissions){
            StatService.onPause(this)
        }
    }

    override fun onResume() {
        super.onResume()
        if(MyApp.privacyPermissions){
            StatService.onResume(this)
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    open fun onBaseEvent(messageEvent: MyEvent) {
        //事件订阅者处理事件
        if (messageEvent.hashMap != null) {
            val map: HashMap<String, String?> = messageEvent.hashMap
            if (map.containsKey("code") && map.containsKey("msg")) {
                if (!MyApp.TokenStatus) {
                    MyApp.TokenStatus = true
                    Token.quit()
                    infoToast(map.get("msg").toString())
                    if (map.get("code")?.equals("4009")!!) {
                        InitDialog(mContext!!,
                            "提示",
                            mContext!!.getString(R.string.no_money),
                            "确定",
                            false,
                            ShareDialogListener {
                                startActivity<LoginActivity>()
                                finish()
                            }).show()

                    } else {
                        startActivity<LoginActivity>()
                    }

                }
            }
        } else {
            val msg = messageEvent.message
            if (msg == "Failure") {
                if (!MyApp.TokenStatus) {
                    MyApp.TokenStatus = true
                    Token.quit()
                    infoToast("登陆信息已过期, 请重新登陆.")
                    startActivity<LoginActivity>()
                }
            } else if (msg == "NoMoney") {
                //顶部状态栏 处理
                InitDialog(mContext!!, "提示", mContext!!.getString(R.string.no_money), "确定", false,
                    ShareDialogListener {
                        startActivity<LoginActivity>()
                    }).show()
            }
        }
    }
}